<template>
  <div class="app-container">
    <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
      label-width="120px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="用户名" prop="userNameLike">
            <el-input
              v-model="queryParams.userNameLike"
              placeholder="请输入用户名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请假天数" prop="leaveDays">
            <el-input
              v-model="queryParams.leaveDays"
              placeholder="请输入请假天数"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审批状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择审批状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <search-button @click="handleQuery" :perm="['samples:leave:search']" />
            <reset-button @click="resetQuery" :perm="['samples:leave:search']" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['samples:leave:insert']" :roleType="['app']" />
      <delete-button
        @click="handleDelete"
        :disabled="multiple"
        :perm="['samples:leave:delete']"
        :roleType="['app']"
      />
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
        :perm="['samples:leave:search']"
      />
    </el-row>

    <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="申请ID"
        prop="applyId"
        :show-overflow-tooltip="true"
        min-width="100"
      />
      <el-table-column label="用户ID" prop="userId" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column
        label="用户名"
        prop="userName"
        :show-overflow-tooltip="true"
        min-width="100"
      />
      <el-table-column
        label="请假天数"
        prop="leaveDays"
        :show-overflow-tooltip="true"
        min-width="100"
      />
      <el-table-column label="审批状态" prop="status" align="center" min-width="200">
        <template #default="scope">{{ selectDictLabel(statusOptions, scope.row.status) }}</template>
      </el-table-column>
      <el-table-column label="创建者" prop="createBy" align="center" width="120" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="160" />
      <el-table-column label="更新者" prop="updateBy" align="center" width="120" />
      <el-table-column label="更新时间" prop="updateTime" align="center" width="160" />
      <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" min-width="100" />
      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
        v-if="hasRoleType(['app'])"
      >
        <template #default="scope">
          <div v-if="scope.row.status != '02'">
            <text-edit-button
              @click="handleUpdate(scope.row)"
              :perm="['samples:leave:update']"
              :roleType="['app']"
            />
            <text-delete-button
              @click="handleDelete(scope.row)"
              :perm="['samples:leave:delete']"
              :roleType="['app']"
              :title="'是否确认删除记录' + scope.row.applyId + '?'"
            />
          </div>
          <sapn v-else> - </sapn>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或修改对话框 -->
    <el-dialog
      :title="editForm.title"
      :close-on-click-modal="false"
      v-model="editForm.open"
      width="800px"
      append-to-body
    >
      <el-form ref="formRef" :model="editForm.data" :rules="editForm.rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="请假天数" prop="leaveDays">
              <el-input v-model="editForm.data.leaveDays" placeholder="请输入请假天数" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="editForm.data.remark"
                placeholder="请输入备注"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" okText="暂 存">
          <template #end>
            <el-button type="warning" @click="submitWf">直接提交</el-button>
            <el-button type="success" @click="selectAndSubmitWf">选人提交</el-button>
          </template>
          <!-- <template #end>
            <el-button type="success" @click="selectAndSubmitWf">选人提交</el-button>
          </template> -->
        </dialog-footer>
      </template>
    </el-dialog>

    <!-- 选择下一步处理人对话框 -->
    <select-next-user
      :selectUserParam="selectUserParam"
      :visible="selectUserOpen"
      @selected="doSelected"
      @close="selectUserOpen = false"
    />
  </div>
</template>

<script>
import {
  search,
  insert,
  deleteByIds,
  updateById,
  selectById,
  startWfInstanceAndCompleteFirst
} from '@samples/api/samples/leave'
import { debounceWrapper } from '@/utils/zmids'

export default {
  // 此处的名字需要与菜单中Path一致，否则多Tab页切换时会刷新
  name: 'SamplesLeave',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 审批状态的数据字典选项列表：samples_leave_status
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 申请ID
        applyId: undefined,
        // 用户ID
        userId: undefined,
        // 用户名
        userNameLike: '',
        // 请假天数
        leaveDays: undefined,
        // 审批状态
        statusLike: '',
        // 创建者
        createByLike: '',
        // 创建时间
        createTime: undefined,
        // 更新者
        updateByLike: '',
        // 更新时间
        updateTime: undefined,
        // 备注
        remarkLike: ''
      },
      editForm: {
        // 控制 dialog
        open: false,
        // 弹出层标题
        title: '',
        // 表单参数
        data: {},
        // 规则
        rules: {
          // 用户ID
          userId: [{ required: true, message: '用户ID不可以为空', trigger: 'blur' }],
          // 用户名
          userName: [
            { required: true, message: '用户名不可以为空', trigger: 'blur' },
            { min: 1, max: 64, message: '用户名的长度最多 64 个字符', trigger: 'blur' }
          ],
          // 请假天数
          leaveDays: [{ required: true, message: '请假天数不可以为空', trigger: 'blur' }],
          // 审批状态
          status: [
            { required: true, message: '审批状态不可以为空', trigger: 'blur' },
            { min: 1, max: 16, message: '审批状态的长度最多 16 个字符', trigger: 'blur' }
          ]
        }
      },
      // 选择下一步处理弹框需要的参数
      selectUserParam: {},
      // 选择下一步处理弹框是否显示的参数
      selectUserOpen: false
    }
  },
  created() {
    // 查询列表
    this.getList()

    // 获取数据字典：samples_leave_status
    this.getDicts('samples_leave_status').then((response) => {
      this.statusOptions = response.data
    })
  },
  methods: {
    // 查询列表
    getList: debounceWrapper(function () {
      this.loading = true
      search(this.queryParams).then((response) => {
        this.dataList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    }),
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 表单重置
    reset() {
      this.editForm.data = {
        // 申请ID
        applyId: undefined,
        // 用户ID
        userId: undefined,
        // 用户名
        userName: '',
        // 请假天数
        leaveDays: undefined,
        // 审批状态
        status: '',
        // 创建者
        createBy: '',
        // 创建时间
        createTime: undefined,
        // 更新者
        updateBy: '',
        // 更新时间
        updateTime: undefined,
        // 备注
        remark: ''
      }
      // 重置字段校验
      this.$refs.formRef && this.$refs.formRef.clearValidate()
      this.resetForm('formRef')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 所有选中的ID
      this.ids = selection.map((item) => item.applyId)
      // 激活多选删除
      this.multiple = !selection.length
    },
    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.editForm.open = true
      this.editForm.title = '新增示例：请假申请流程'
    },
    // 删除按钮操作
    handleDelete: debounceWrapper(function (row) {
      const deleteIds = row ? row.applyId : this.ids.join(',')
      deleteByIds(deleteIds)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    }),
    // 修改按钮操作
    handleUpdate: debounceWrapper(function (row) {
      this.reset()
      selectById(row.applyId).then((response) => {
        this.editForm.data = response.data
        this.editForm.open = true
        this.editForm.title = '修改示例：请假申请流程'
      })
    }),
    // 提交按钮
    submitForm: debounceWrapper(function () {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          // 创建者
          delete this.editForm.data.createBy
          // 创建时间
          delete this.editForm.data.createTime
          // 更新者
          delete this.editForm.data.updateBy
          // 更新时间
          delete this.editForm.data.updateTime

          const ifUpdate = this.editForm.data.applyId != undefined
          const promise = ifUpdate ? updateById(this.editForm.data) : insert(this.editForm.data)
          promise.then((response) => {
            if (response.data === 1) {
              this.msgSuccess(ifUpdate ? '修改成功' : '新增成功')
              this.editForm.open = false
              this.getList()
            }
          })
        }
      })
    }),
    // 取消按钮
    cancel() {
      this.editForm.open = false
      this.reset()
    },
    // 直接发起流程，不选择下一步处理人
    submitWf: debounceWrapper(function () {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          /**
           * 不选择下一步处理人，则流程会直接启动，根据配置的参与人，流程引擎自动计算参与人集合，
           * 会向所有人发送待办，非会签节点则只要有一人审批则流程继续，会签节点根据配置按比例通过则流程继续
           */
          this.$confirm('是否确认直接提交流程', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              //直接启动流程
              startWfInstanceAndCompleteFirst(this.editForm.data).then((response) => {
                this.msgSuccess('流程提交成功')
                this.editForm.open = false
                this.getList()
              })
            })
            .catch((e) => {
              console.error(e)
            })
        }
      })
    }),
    // 选择下一步处理人按钮
    selectAndSubmitWf: debounceWrapper(function () {
      const params = {
        wfCode: 'SAMPLES_LEAVE',
        completeFirst: true
      }
      this.wfClient.isNeedSelectUser(
        'SAMPLES_LEAVE',
        null,
        null,
        null,
        params,
        () => {
          //选择下一步处理
          this.selectUserParam = params
          this.selectUserOpen = true
        },
        () => {
          //直接启动流程
          startWfInstanceAndCompleteFirst(this.editForm.data).then((response) => {
            this.msgSuccess('流程提交成功')
            this.editForm.open = false
            this.getList()
          })
        }
      )
    }),
    // 选中用户
    doSelected(candidates) {
      this.selectUserOpen = false
      //直接启动流程
      startWfInstanceAndCompleteFirst({
        ...this.editForm.data,
        params: {
          candidates: candidates.join(',')
        }
      }).then((response) => {
        this.msgSuccess('流程提交成功')
        this.editForm.open = false
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
